using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Linq;
using xiushen.Infrastructure;
using xiushen.Utilies;

namespace xiushen.Domain
{
    public interface IAdminService
    {
        bool ValiDateUser(string userName, string password);
        T PersistData<T>(T data) where T : EntityObject;
        Category PersitCatalog(Category data);
        Book PersitBook(Book data);
        Attachment SaveAttachMent(Attachment data);
        IEnumerable<Category> GetAllCategorys(bool isChildren = true, bool containImage = false);
    }

    public class AdminRepository : Repository<Category>, IAdminService
    {
        public bool ValiDateUser(string userName, string password)
        {
            var data = QueryAll<Users>().Where(r => r.Name == userName).FirstOrDefault();
            if (data == null) return false;
            var passwordHash = Encryptor.MD5Hash(password,data.Salt);
            return passwordHash == data.PasswordHash;
        }

        public T PersistData<T>(T data) where T : EntityObject
        {
           
            return  Persist(data);
        }
        public Category PersitCatalog(Category data)
        {
            int id = 0;
            if (QueryAll<Category>().Count() > 0)
            {
                id = QueryAll<Category>().Max(r => r.ID);
            }
            data.ID = ++id;

           return Persist(data);

        }
        public Book PersitBook(Book data)
        {
            int id = 0;
            if (QueryAll<Book>().Count() > 0)
            {
                id = QueryAll<Book>().Max(r => r.ID);
            }
            data.ID = ++id;
            return Persist(data);

        }

        public Attachment SaveAttachMent(Attachment data)
        {
            throw new System.NotImplementedException();
        }

        public IEnumerable<Category> GetAllCategorys(bool isChildren = true,bool containImage = false)
        {
            if (isChildren)
                return QueryAll().Where(r => r.ParentID != null || (containImage &&r.Type == Constants.Image)).ToList();

            return QueryAll().Where(r => r.ParentID == null).ToList();
        }
    }

}